<style lang="scss" scoped>
  .form-submit{
    margin: .32rem;
  }
</style>

<template>
  <div class="container hasNav">
    <van-nav-bar :title="title" left-arrow left-text="返回" @click-left="$router.back()" fixed >
      <template #right>
        <div
            style="color: #ee0a24;"
            @click="delInfo"
            v-if="(type === 1 && !!userInfo.bankCardNumber) || (type === 2 && !!userInfo.alipayCardNumber)">删除</div>
      </template>
    </van-nav-bar>

    <div class="card-form">
      <van-form
          v-if="type === 1"
          :show-error="false"
          :show-error-message="false"
          ref="bankForm"
      >
        <van-field
            v-model="form.bankCardNumber"
            type="text"
            name="bankCardNumber"
            label="银行卡号"
            placeholder="请输入银行卡号"
            :maxlength="19"
            :rules="[{ required: true, message: '请填写银行卡号' }]"
        />
        <van-field
            readonly
            clickable
            v-model="form.bankName"
            name="bankName"
            label="开户行"
            placeholder="请选择"
            @click="showPicker = true"
            :rules="[{ required: true, message: '请选择开户行' }]"
        />
        <van-field
            v-model="form.bankAddress"
            type="text"
            name="bankAddress"
            label="开户行地址"
            placeholder="请输入开户行地址"
            :rules="[{ required: true, message: '请填写开户行地址' }]"
        />
        <van-field
            v-model="form.payeeName"
            type="text"
            name="payeeName"
            label="持卡人"
            placeholder="未设置"
            :rules="[{ required: true, message: '请填写持卡人' }]"
        />
      </van-form>

      <van-form
          ref="alipayForm"
          :show-error="false"
          :show-error-message="false"
          v-else>
        <van-field
            v-model.trim="form.alipayCardNumber"
            type="text"
            name="alipayCardNumber"
            label="支付宝账号"
            placeholder="请输入支付宝账号"
            :rules="[{ required: true, message: '请填写支付宝账号' }]"
        />
        <van-field
            v-model.trim="form.alipayName"
            type="text"
            name="alipayName"
            label="收款人"
            placeholder="请输入收款人"
            :rules="[{ required: true, message: '请填写收款人' }]"
        />
      </van-form>
      <div class="form-submit">
        <van-button block type="default" color="#179AFE" @click="onSubmit">提交</van-button>
      </div>
    </div>

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
          show-toolbar
          :columns="columns"
          @confirm="onConfirm"
          @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  import {
    saveBankInfo,
    delBankInfo,
    getBankList,
    saveAlipayInfo,
    delAlipayInfo
  } from "../../api/user";

  export default {
    name: 'CardAdd',
    data() {
      return {
        id: null,
        type: 1, // 1 银行卡 2 支付宝
        title: '输入银行卡信息',
        form: {
          bankCardNumber: null,
          bankAddress: null,
          bankName: null,
          payeeName: null,

          alipayName: null,
          alipayCardNumber: null
        },
        depositList: [
          {
            label: '兴业银行',
            value: 0
          }
        ],
        showPicker: false
      };
    },
    mounted() {
      this.id = this.$route.params.id || null;
      this.type = +this.$route.query.type
      if(this.type === 1) {
        this.title = '输入银行卡信息'
        this.getDepositList()
        this.getBankInfo()
      } else {
        this.title = '填写支付宝信息'
        this.getAlipayInfo();
      }
    },
    computed: {
      ...mapGetters(['userInfo']),
      columns() {
        return this.depositList.map(k => k.label)
      }
    },
    methods: {
      async getDepositList() {
        const { banklist } = await getBankList()
        this.depositList = banklist.map(k => {
          return {
            label: k.bankname,
            value: k.bankname
          }
        })
      },
      onConfirm(value) {
        this.form.bankName = value;
        this.showPicker = false;
      },
      onSubmit() {
        this.type === 1 ? this.saveBackInfo() : this.saveAlipayInfo()
      },
      getAlipayInfo() {
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        if(!!userInfo.alipayCardNumber) {
          this.form.alipayName = userInfo.alipayName
          this.form.alipayCardNumber = userInfo.alipayCardNumber
        }
      },
      getBankInfo() {
        let userInfo = JSON.parse(JSON.stringify(this.userInfo))
        if(!!userInfo.bankCardNumber) {
          this.form.bankCardNumber = userInfo.bankCardNumber
          this.form.bankAddress = userInfo.bankAddress
          this.form.bankName = userInfo.bankName
          this.form.payeeName = userInfo.payeeName
        }
      },
      saveAlipayInfo() {
        this.$refs.alipayForm.validate().then(async () => {
          console.log(this.form.alipayCardNumber)
          if(this.form.alipayCardNumber.includes('@')) {
            if(!/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(this.form.alipayCardNumber)) {
              return this.$toast('请填写正确的邮箱地址')
            }
          } else {
            if(!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.form.alipayCardNumber)) {
              return this.$toast('请填写11位正确的手机号')
            }
          }
          let params = {
            alipayName: this.form.alipayName,
            alipayCardNumber: this.form.alipayCardNumber
          }

          const { errorcode, errormsg } = await saveAlipayInfo(params);
          if(!errorcode) {
            this.$toast('支付宝绑定成功!')
            this.$router.go(-1)
          } else {
            this.$toast(errormsg)
          }
        }).catch(err => {
          if(err && err.length) {
            this.$toast(err[0].message)
          }
        })
      },
      async delInfo() {
        this.$dialog.confirm({
          message: `确认要删除当前${this.type === 1 ? '银行卡信息' : '支付宝信息'}吗?`,
        })
          .then(async () => {
            if(this.type === 1) {
              const { errorcode, errormsg } = await delBankInfo();
              if(!errorcode) {
                this.$toast('删除成功!')
                this.$router.go(-1)
              } else {
                this.$toast(errormsg)
              }
            } else {
              const { errorcode, errormsg } = await delAlipayInfo();
              if(!errorcode) {
                this.$toast('删除成功!')
                this.$router.go(-1)
              } else {
                this.$toast(errormsg)
              }
            }
          })
          .catch(() => {
            console.log('取消')
          });
      },
      async saveBackInfo() {
        this.$refs.bankForm.validate().then(async () => {
          if(this.form.bankCardNumber.length > 19 || this.form.bankCardNumber.length < 16) {
            return this.$toast('请填写正确的银行卡号')
          }

          let params = {
            bankCardNumber: this.form.bankCardNumber,
            bankAddress: this.form.bankAddress,
            bankName: this.form.bankName,
            payeeName: this.form.payeeName
          }

          const { errorcode, errormsg } = await saveBankInfo(params);
          if(!errorcode) {
            this.$toast('银行卡绑定成功!')
            this.$router.go(-1)
          } else {
            this.$toast(errormsg)
          }
        }).catch(err => {
          if(err && err.length) {
            this.$toast(err[0].message)
          }
        })
      }
    }
  };
</script>
